package com.zmjmall.demo.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zmjmall.demo.api.CategoryService;
import com.zmjmall.demo.model.Category;
import com.zmjmall.demo.vo.CategoryVO;
import com.zmjmall.demo.utils.ResultVOUtil;
import com.zmjmall.demo.utils.TreeParser;
import com.zmjmall.demo.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品分类控制层
 *
 * @author zmj
 * @version 2018/7/2
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Reference
    private CategoryService categoryService;

    /**
     * 获取所有分类
     * @return
     */
    @GetMapping
    @ResponseBody
    public ResultVO<Category> findAll() {
        List<Category> list = categoryService.findAll();
        return ResultVOUtil.success(list);
    }

    /**
     * 通过分类id获取单个分类
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ResponseBody
    public ResultVO findAll(@PathVariable String id) {
        Category category = categoryService.findById(id);
        return ResultVOUtil.success(category);
    }


    @PostMapping("/findMenuLeave")
    @ResponseBody
    public ResultVO findMenuLeave(@Valid Category category){
        List<Category> menuList = categoryService.findMenuLeave(category);
        if(menuList == null){
            ResultVOUtil.error(-1,"暂无数据");
        }
        return ResultVOUtil.success(menuList);
    }

    @PostMapping("/findPost")
    @ResponseBody
    public ResultVO findPost(@Valid Category category){
        List<Category> menuList = categoryService.findMenuLeave(category);
        return ResultVOUtil.success(menuList);
    }

    @PostMapping("/findChildCategory")
    @ResponseBody
    public ResultVO findChildCategory(@RequestParam(defaultValue = "0",required = false) String cid){

        List<CategoryVO> list=new ArrayList<>();
        List<Category> categorys = categoryService.findChildCategory();
        for(Category item : categorys){
            CategoryVO TempCategoryVO=new CategoryVO();
            TempCategoryVO.setId(item.getId());
            TempCategoryVO.setName(item.getCategoryName());
            TempCategoryVO.setParentId(item.getPid());
            TempCategoryVO.setImg(item.getImage());
            list.add(TempCategoryVO);
        }
        List<CategoryVO>  CategoryVOs = TreeParser.getTreeList(cid,list);
        return ResultVOUtil.success(CategoryVOs);
    }

}
